#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "mythread.hpp"
using namespace ThreadMoudle;

void SendMessage(int sockfd, std::string ip, uint16_t port, std::string name)
{
    while (true)
    {
        struct sockaddr_in peer;

        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        peer.sin_addr.s_addr=inet_addr(ip.c_str());

        std::string cli_profix = name + "# "; // sender-thread# 你好
        std::string message;
        std::cout << cli_profix;
        std::getline(std::cin, message);
        int n = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&peer, sizeof(peer));
        if(n<0)
        break;
    }
}

void RecvMessage(int sockfd, std::string name)
{
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        memset(&peer, 0, sizeof(peer));
        char buffer[1024];
        int n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer <<std::endl;
        }
        else
        {
            std::cerr << "recvfrom error" << std::endl;
            break;
        }
    }
}
// ./udp_client 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(1);
    }

    thread recv_thread("recv_thread", std::bind(&RecvMessage, sockfd, std::placeholders::_1));
    thread send_thread("send_thread", std::bind(&SendMessage, sockfd, serverip, serverport, std::placeholders::_1));

    send_thread.start();
    recv_thread.start();
    send_thread.join();
    recv_thread.join();

    close(sockfd);
    return 0;
}